<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\middleware\Auth;
use app\model\Contact as ModelContact;
use app\model\Region;
use app\model\Type;
use app\model\User;
use think\facade\Validate;
use think\facade\View;

class Contact extends BaseController
{
    protected $middleware = [
        Auth::class
    ];

    protected function initialize()
    {
        parent::initialize();

        $this->RegionModel = new Region();

        $this->ContactModel = new ModelContact();

        $this->TypeModel = new Type();

        $this->UserModel = new User();
    }

    // 新增数据
    public function add()
    {
        if($this->request->isPost())
        {
            // 接收全部的参数
            $params = $this->request->param();

            // 查询地区码
            $parentpath = $this->RegionModel->where(['code' => $params['district']])->value('parentpath');

            // 查询的地区码是否存在
            if(!$parentpath)
            {
                $this->error('所选地区不存在');
                halt();
            }

            // 封装插入的数据
            $data = [
                'userid' => request()->LoginUser['id'],
                'typeid' => $params['typeid'],
                'nickname' => $params['nickname'],
                'phone' => $params['phone'],
                'gender' => $params['gender'],
                'region' => $parentpath,
                'remark' => $params['remark']
            ];

            // 验证器
            $validate = Validate::rule('app\validate\Contact');

            // 是否通过验证
            if(!$validate->check($data))
            {
                $this->error($validate->getError());
                halt();
            }

            $result = $this->ContactModel->save($data);

            if($result === FALSE)
            {
                $this->error('新增失败');
                halt();
            }else{
                $this->success('新增成功', '/index/index');
                halt();
            }

        }

        // 查询省份地区的数据
        $province = $this->RegionModel->where(['grade' => 1])->select();

        // 查询分类的数据
        $TypeList = $this->TypeModel->order('id','desc')->select();

        return View::fetch('',[
            'province' => $province,
            'TypeList' => $TypeList
        ]);
    }

    // 详情
    public function info()
    {
        $conid = $this->request->param('conid',0);

        $Contact = $this->ContactModel->find($conid);

        if(!$Contact)
        {
            $this->error('该联系人不存在');
            halt();
        }

        [$province,$city,$district] = explode(',',$Contact['region']);
        
        $Contact['province'] = $province;

        $Contact['city'] = $city;

        $Contact['district'] = $district;

        
        // 查询分类的数据
        $TypeList = $this->TypeModel->order('id','desc')->select();

        // 查询省份地区的数据
        $provinces = $this->RegionModel->where(['grade' => 1])->select();

        if(empty($province))
        {
            $citys = [];
        }else{
            $citys = $this->RegionModel->where(['parentid' => $province])->select();
        }

        if(empty($city))
        {
            $districts = [];
        }else {
            $districts = $this->RegionModel->where(['parentid' => $city])->select();
        }

        return View::fetch('',[
            'provinces' => $provinces,
            'citys' => $citys,
            'districts' => $districts,
            'TypeList' => $TypeList,
            'Contact' => $Contact
        ]);
    }

    // 编辑
    public function edit()
    {
        if($this->request->isPost())
        {
            // 接收所有的参数
            $params = $this->request->param();

            // 先查询数据是否存在
            $Contact = $this->ContactModel->find($params['conid']);

            if(!$Contact)
            {
                $this->error('该联系人不存在，请重新选择');
                halt();
            }

            // 查询出来不包括自身的其他数据
            $ContactList = $this->ContactModel->where([['id','<>', $params['conid']]])->select();

            // 数据循环出来，判断修改的昵称是否已经存在在数据库里
            foreach($ContactList as $item)
            {
                if($item['nickname'] == $params['nickname'])
                {
                    $this->error('昵称已存在，请重新输入');
                    // halt();
                    break;
                }
            }

            // 判断修改的手机号是否已经存在在数据库里
            // foreach($ContactList as $item)
            // {
            //     if($item['phone'] == $params['phone'])
            //     {
            //         $this->error('手机号已存在，请重新输入');
            //         break;
            //     }
            // }

            // 查询地区码
            $parentpath = $this->RegionModel->where(['code' => $params['district']])->value('parentpath');

            // 查询的地区码是否存在
            if(!$parentpath)
            {
                $this->error('所选地区不存在');
                halt();
            }

            // 封装插入的数据
            $data = [
                'userid' => request()->LoginUser['id'],
                'typeid' => $params['typeid'],
                'nickname' => $params['nickname'],
                'phone' => $params['phone'],
                'gender' => $params['gender'],
                'region' => $parentpath,
                'remark' => $params['remark']
            ];

            $result = $this->ContactModel->where(['id' => $params['conid']])->save($data);
            
            if($result == FALSE)
            {
                $this->error('更新失败');
                halt();
            }else{
                $this->success('更新成功','/index/index');
                halt();
            }

        }
    }

    // 删除
    public function del()
    {
        if($this->request->isAjax())
        {
            $id = $this->request->param('id',0);

            $Contact = $this->ContactModel->find($id);

            if(!$Contact)
            {
                $this->error('该联系人不存在，无法删除');
                halt();
            }

            $res = $this->ContactModel->where('id',$id)->delete($id);

            if($res == FALSE)
            {
                $this->error('删除失败');
                halt();
            }else{
                $this->success('删除成功');
                halt();
            }
        }
    }

    // 通过ajax查询地区
    public function area()
    {
        if($this->request->isAjax())
        {
            // 地区码
            $code = $this->request->param('code',0);

            // 接收方法参数
            $action = $this->request->param('action','');

            // 是否选择省份
            if($action == 'province')
            {
                $CityList = $this->RegionModel->where(['parentid' => $code])->select();

                // 返回的数据
                $data = [
                    'CityList' => $CityList,
                ];

                // 获取选中省份后的第一个市
                $CityCode = !empty($CityList[0]['code']) ? $CityList[0]['code'] : 0;

                if($CityCode)
                {
                    // 获取第一个市的所有区
                    $data['DistrictList'] = $this->RegionModel->where(['parentid' => $CityCode])->select();
                }
            }else{
                $data = $this->RegionModel->where(['parentid' => $code])->select();
            }

            $this->success('返回数据成功',null,$data);
            
        }
    }

    // 查询手机号是否存在
    public function phone()
    {
        if($this->request->isAjax())
        {
            $phone = $this->request->param('phone','');

            $user = $this->ContactModel->where(['phone' => $phone])->find();

            if($user)
            {
                $this->error('该手机号已经存在，请重新输入');
                halt();
            }else {
                $this->success('该手机号可以注册');
                halt();
            }
        }
    }
}
